package com.zsh.rabbitmq.four;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import com.zsh.rabbitmq.utils.RabbitMQUtils;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * @author zsh
 * @Description 验证发布确认模式  使用的时间 比较哪种方式最好
 *      1. 单个确认模式
 *      2. 批量确认模式
 *      3. 异步批量确认模式
 * @create 2022-05-05 15:28
 */
public class ConfirmMessage {

    //批量发消息的个数
    public static final int MESSAGE_COUNT = 1000;

    public static void main(String[] args) throws Exception {
        //1. 单个确认
        //ConfirmMessage.publishMessageIndividually(); //发布1000个单独确认消息耗时，568ms
        //2. 批量确认
        //ConfirmMessage.publishMessageBatch(); //发布1000个批量确认消息耗时，63ms
        //3. 异步批量
        ConfirmMessage.publishMessageAsync(); //发布1000个异步发布确认消息耗时，22ms
    }

    //单个确认
    public static void publishMessageIndividually() throws Exception {
        Channel channel = RabbitMQUtils.getChannel();

        //队列的声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);

        //开启发布确认模式
        channel.confirmSelect();
        //开始时间
        long begin = System.currentTimeMillis();

        //批量发消息
        for (int i = 0; i < MESSAGE_COUNT ;i++){
            String msg = i + "";
            channel.basicPublish("",queueName,null,msg.getBytes());
            //单个消息马上进行发布确认
            boolean flag = channel.waitForConfirms();
            if (flag){
                System.out.println("消息发布成功！" + i);
            }
        }

        //结束时间
        long end = System.currentTimeMillis();

        System.out.println("发布" + MESSAGE_COUNT + "个单独确认消息耗时，" + (end - begin) + "ms");
    }

    //批量确认
    public static void publishMessageBatch() throws Exception {
        Channel channel = RabbitMQUtils.getChannel();

        //队列的声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);

        //开启发布确认模式
        channel.confirmSelect();
        //开始时间
        long begin = System.currentTimeMillis();

        //批量确认消息的大小
        int batchSize = 100;

        //批量发消息 批量发布确认
        for (int i = 0; i < MESSAGE_COUNT ;i++){
            String msg = i + "";
            channel.basicPublish("",queueName,null,msg.getBytes());

            //判断是否达到一百条消息
            if (i%batchSize == 0){
                //发布确认
                channel.confirmSelect();
            }
        }

        //结束时间
        long end = System.currentTimeMillis();

        System.out.println("发布" + MESSAGE_COUNT + "个批量确认消息耗时，" + (end - begin) + "ms");
    }

    //异步发布
    public static void publishMessageAsync() throws Exception {
        Channel channel = RabbitMQUtils.getChannel();

        //队列的声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);

        //开启发布确认模式
        channel.confirmSelect();

        //线程安全有序的哈希表（map），适用于高并发情况
        /**
         * 1.轻松将序号与消息关联
         * 2.轻松的批量删除已确认消息，通过序号
         * 3.支持高并发
         */
        ConcurrentSkipListMap<Long,String> outstandingConfirms =
                new ConcurrentSkipListMap<>();

        //消息确认成功回调函数
        ConfirmCallback ackCallback = (deliverTag,multiple) ->{
            if (multiple){
                //②.删除掉已确认的消息
                ConcurrentNavigableMap<Long, String> confirmed =
                        outstandingConfirms.headMap(deliverTag);
                confirmed.clear();
            } else {
                outstandingConfirms.remove(deliverTag);
            }

            System.out.println("确认的消息编号" + deliverTag);
        };

        //消息确认失败回调函数
        /**
         *  1.消息标记
         *  2.是否为批量确认
         */
        ConfirmCallback nackCallback = (deliverTag,multiple) ->{
            //③.打印未确认的消息
            String msg = outstandingConfirms.get(deliverTag);
            System.out.println("未确认的消息" + msg  +",未确认的消息编号" + deliverTag);
        };

        //准备消息监听器，监听哪些消息成功了，哪些失败了
        channel.addConfirmListener(ackCallback,nackCallback);  //异步

        //开始时间
        long begin = System.currentTimeMillis();

        //批量发布消息，异步确认
        for (int i = 0; i < MESSAGE_COUNT ; i++) {
            String msg = "消息" + i;
            channel.basicPublish("",queueName,null,msg.getBytes());

            //①.此处记录下所有要发送的消息，消息的总和
            outstandingConfirms.put(channel.getNextPublishSeqNo(),msg);
        }


        //结束时间
        long end = System.currentTimeMillis();

        System.out.println("发布" + MESSAGE_COUNT + "个异步发布确认消息耗时，" + (end - begin) + "ms");
    }
}
